package service

import (
	"core/coreentity"
	"core/coreqto"
	"core/coreservice"
	"core/corestruct"
	"core/coreutil"
	"core/myerrors"
	"gorm.io/gorm"
	"ht/api/htpage/data"
)

type mainService struct {
}

// Page 功能分页
func (p *mainService) Page(mm *coreqto.BasePageDtQto, ctx *corestruct.HttpContext) (*corestruct.Page[data.HtPageDto], error) {
	var db = ctx.DB
	tx := db.Model(&coreentity.HtPage{}).
		Select("HtPage.*,ur.Name as crt_uname,ur2.name as edt_uname").
		Joins("inner join htuser ur on   HtPage.crt_uid=ur.id", "").
		Joins("inner join htuser ur2 on   HtPage.edt_uid=ur2.id", "")
	if mm.Id > 0 {
		tx = tx.Where("HtPage.id=?", mm.Id)
	} else {
		var dtb, _ = mm.GetDtb()
		if dtb != nil {
			tx = tx.Where("HtPage.edt_dt>=?", dtb)
		}

		var dte, _ = mm.GetDte()
		if dte != nil {
			tx = tx.Where("HtPage.edt_dt<?", dte)
		}

		if "" != mm.Key {
			var keyValue = "%" + mm.Key + "%"
			tx = tx.Where("HtPage.name like ? or HtPage.code like ?", keyValue, keyValue)
		}
	}
	var svr = coreservice.PageService[data.HtPageDto]{}
	r, err := svr.Page(&(mm.BasePageQto), ctx, tx)

	if err != nil {
		return nil, myerrors.NewByErr(err)
	}

	return r, nil
}

// ListPageAuth 获取页面对应授权
func (p *mainService) ListPageAuth(pageid int64, ctx *corestruct.HttpContext) (*[]data.HtPageAuthDto, error) {
	var mfind = &coreentity.HtPageAuth{HtpageId: pageid}
	var db = ctx.DB
	var r []data.HtPageAuthDto
	tx := db.Model(mfind).Where(mfind).Order("sortno").Find(&r)
	if tx.Error != nil {
		return nil, myerrors.NewByErr(tx.Error)
	}
	return &r, nil
}

// Detail 功能详情
func (p *mainService) Detail(mm *corestruct.IdModel, ctx *corestruct.HttpContext) (*data.HtPageDto, error) {
	var qto = &coreqto.BasePageDtQto{
		BasePageQto: coreqto.BasePageQto{
			Id:       mm.Id,
			Page:     1,
			PageSize: 1,
		},
	}
	var r, err = p.Page(qto, ctx)
	if err != nil {
		return nil, err
	}
	if r.TotalRow == 0 {
		return nil, myerrors.NewDataNotExist()
	}
	var r1 = &r.Records[0]

	lauth, err := p.ListPageAuth(r1.Id, ctx)
	if err != nil {
		return nil, myerrors.NewByErr(err)
	}
	r1.Auths = *lauth
	return r1, nil
}

// InsertInit 插入初始化
func (p *mainService) InsertInit(ctx *corestruct.HttpContext) (*data.HtPageDto, error) {
	var r = &data.HtPageDto{
		Id:       coreutil.IdUtil.GetId(),
		Code:     "",
		Name:     "",
		Memo:     "",
		Imgurl:   "layui-icon-form",
		Lx:       "",
		P1:       "",
		P2:       "",
		P3:       "",
		P4:       "",
		Auths:    make([]data.HtPageAuthDto, 0),
		CrtDt:    corestruct.Now(),
		CrtUname: "",
		EdtDt:    corestruct.Now(),
		EdtUname: "",
	}

	return r, nil
}

// CheckExistByEname
// 检查角色是不是存在
func (p *mainService) CheckExistByEname(code string, id int64, ctx *corestruct.HttpContext) (bool, error) {
	var m = &coreentity.HtPage{Code: code}
	tx := ctx.DB.Where(m).
		Select("id").
		Where("id!=?", id).
		Find(m)
	if tx.Error != nil {
		return false, tx.Error
	}
	return m.Id > 0, nil
}

// Insert
// 插入用户
func (p *mainService) Insert(mm *data.HtPageDto, ctx *corestruct.HttpContext) (int64, error) {
	bExist, myerr := p.CheckExistByEname(mm.Name, mm.Id, ctx)
	if myerr != nil {
		return 0, myerr
	}
	if bExist == true {
		return 0, myerrors.New("页面Code重复")
	}

	var db = ctx.DB

	err := db.Transaction(func(tx *gorm.DB) error {

		for _, dto := range mm.Auths {
			tx2 := coreservice.BaseService.InsertByDto(dto, &coreentity.HtPageAuth{}, tx)
			if tx2.Error != nil {
				return tx2.Error
			}
		}

		tx2 := coreservice.BaseService.InsertByDto(mm, &coreentity.HtPage{}, tx)
		if tx2.Error != nil {
			return tx2.Error
		}

		return nil
	})

	if err != nil {
		return 0, myerrors.NewByErr(err)
	}
	return mm.Id, nil
}

// Update
// 修改用户
func (p *mainService) Update(mm *data.HtPageDto, ctx *corestruct.HttpContext) (int64, error) {
	bExist, myerr := p.CheckExistByEname(mm.Name, mm.Id, ctx)
	if myerr != nil {
		return 0, myerr
	}
	if bExist == true {
		return 0, myerrors.New("页面Code重复")
	}

	var db = ctx.DB

	var loldid []int64
	err := db.Model(&coreentity.HtPageAuth{}).Where("htpage_id=?", mm.Id).
		Find(&loldid).Error
	if err != nil {
		return 0, myerrors.NewByErr(err)
	}
	var lnewid = make([]int64, 0)
	for _, v := range mm.Auths {
		lnewid = append(lnewid, v.Id)
	}

	var lidadd = coreutil.ArrayUtil.IdsNotIn(lnewid, loldid)
	var liddel = coreutil.ArrayUtil.IdsNotIn(loldid, lnewid)

	err = db.Transaction(func(tx *gorm.DB) error {
		for _, auth := range mm.Auths {
			if coreutil.ArrayUtil.IdIn(mm.Id, lidadd) {
				tx2 := coreservice.BaseService.InsertByDto(auth, &coreentity.HtPageAuth{}, tx)
				if tx2.Error != nil {
					return tx2.Error
				}
			}
		}

		//删除菜单
		for _, delid := range liddel {
			tx2 := coreservice.BaseService.Delete(&coreentity.HtPageAuth{Id: delid}, tx)
			if tx2.Error != nil {
				return tx2.Error
			}
		}

		tx2 := coreservice.BaseService.UpdateByDto(mm, &coreentity.HtPage{Id: mm.Id}, tx)
		if tx2.Error != nil {
			return tx2.Error
		}
		return nil
	})

	if err != nil {
		return 0, myerrors.NewByErr(err)
	}
	coreservice.BaseService.DeleteCacheById(mm.Id)
	return mm.Id, nil
}

var (
	MainService = &mainService{}
)
